package cn.sumpu.app.guoguojie.util;

import java.io.*;
import java.util.*;

public class HandleFile {

	private static ArrayList<String> list = new ArrayList<String>();
	
	/**
	 * author BruceZhang
	 * @param absolutePath
	 * @param pathName
	 * @return	取得这个文件夹下的所有文件的绝对路径
	 *  调用事例：String fileName = "/home/james/work/guoguojie/guoguojie-web/src/main/webapp/WEB-INF/views/v2";
	 *			List<String> fileList = getFilesName(fileName, "");
	 */
	private static List<String> getFilesName(String absolutePath, String pathName){
		File file = new File(absolutePath+pathName);
		String[] filesName = file.list();
		int i = 0;
		while(filesName!=null && i<filesName.length){
			String fileName = filesName[i];
			if(fileName.charAt(0)!='.'){
				getFilesName(absolutePath+"/"+pathName, fileName+"/");
			}
			i++;
		}
		if(filesName==null){
			String temp = (absolutePath+"/"+pathName).replace("//", "/");
			list.add(temp.substring(0, temp.length()-1));
		}
		return list;
	}
	
	//读取文件
	public static String readFileContent(String pathName){
		try {
			FileInputStream fis = new FileInputStream(pathName);
			InputStreamReader isr = new InputStreamReader(fis);
			BufferedReader br = new BufferedReader(isr);
			String str;
			StringBuffer sb = new StringBuffer("");
			while((str=br.readLine())!=null){
				sb.append(str+"\r");
			}
			br.close();
			isr.close();
			fis.close();
			return sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	//写入文件
	public static void writeFileContent(String pathName, String content){
		try {
			FileOutputStream fos = new FileOutputStream(pathName);
			OutputStreamWriter osw = new OutputStreamWriter(fos);
			BufferedWriter bw = new BufferedWriter(osw);
			bw.write(content);
			bw.close();
			osw.close();
			fos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//替换这个文件夹下的某个标记
	private static void replaceFileContent(String pathName, String oldStr, String newStr){
		System.out.println("开始替换......");
		List<String> fileList = getFilesName(pathName, "");
		int count = 0;
		for(String file : fileList){
			String fileContent = readFileContent(file);
			if(fileContent.indexOf(oldStr)==-1){
				continue;
			}
			writeFileContent(file, fileContent.replace(oldStr, newStr));
			count++;
		}
		System.out.println("成功，"+count+"个文件受影响！");
	}
	
	public static void main(String[] args) {
		replaceFileContent("/home/james/work/guoguojie/guoguojie-web/src/main/java","request.getRemoteAddr()","Common.getIp(request)");
	}
	
}
